"use strict";
var canvas
var gl;

var colors = [
    vec4(0.0, 0.0, 0.0, 1.0),  // black
    vec4(1.0, 0.0, 0.0, 1.0),  // red
    vec4(1.0, 1.0, 0.0, 1.0),  // yellow
    vec4(0.0, 1.0, 0.0, 1.0),  // green
    vec4(0.0, 0.0, 1.0, 1.0),  // blue
    vec4(1.0, 0.0, 1.0, 1.0),  // magenta
    vec4(0.0, 1.0, 1.0, 1.0)   // cyan
];

var index = 0;
var color_index = 0;
var size = 5;

var redraw;
var maxNumTriangles = 10000;
var table_size = (3 + 4 + 2) * 4
var maxNumVertices = table_size * maxNumTriangles;

window.onload = function init()
{
    //创建WebGl上下文对象
    canvas = document.getElementById("gl-canvas");
    gl = WebGLUtils.setupWebGL(canvas);

    if (!gl){
        alert("GG");
    }

    gl.viewport(0, 0, canvas.width, canvas.height);
    // gl.clearColor(1.0, 1.0, 1.0, 1.0);
    gl.clearColor(0.5, 0.5, 0.5, 1.0);

    //创建一个程序对象容器
    var program = initShaders(gl, "vertex-shader", "fragment-shader");  //初始化和绑定 定点着色器 片元着色器
                                                                        //定点着色器 片元着色器 是标准文本（字符串），在初始化时编译，并连接到程序对象中

    gl.useProgram(program);

    var vBuffer = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
    gl.bufferData(gl.ARRAY_BUFFER, maxNumVertices, gl.STATIC_DRAW );

    var vPosition = gl.getAttribLocation( program, "vPosition" );
    gl.vertexAttribPointer(vPosition, 3, gl.FLOAT, false, table_size, 0);
    gl.enableVertexAttribArray( vPosition );

    var vColor = gl.getAttribLocation( program, "vColor" );
    gl.vertexAttribPointer(vColor, 4, gl.FLOAT, false, table_size, 3 * 4);
    gl.enableVertexAttribArray( vColor );

    var vSize = gl.getAttribLocation(program, "vSize");
    gl.vertexAttribPointer(vSize, 1, gl.FLOAT, false, table_size, (3 + 4) * 4);
    gl.enableVertexAttribArray(vSize);

    var m = document.getElementById("mymenu");

    m.addEventListener("click", function () {
        color_index = m.selectedIndex;
    });

    document.getElementById("slider").onchange = function (event) {
        size = parseInt(event.target.value);
        // print_text(size + "<br>")
    };

    canvas.addEventListener("mousedown", function (event) {
        redraw = true;
    });

    canvas.addEventListener("mouseup", function (event) {
        redraw = false;
    });
    //canvas.addEventListener("mousedown", function(){
    canvas.addEventListener("mousemove", function (event) {
        if (redraw && index < maxNumTriangles) {
            var starting_position = table_size * index

            var t = vec3(2 * event.clientX / canvas.width - 1, 2 * (canvas.height - event.clientY) / canvas.height - 1, 0);
            gl.bufferSubData(gl.ARRAY_BUFFER, starting_position, flatten(t));

            t = vec4(colors[color_index]);
            gl.bufferSubData(gl.ARRAY_BUFFER, starting_position + (3 * 4), flatten(t));

            t = vec2(size, 0);
            gl.bufferSubData(gl.ARRAY_BUFFER, starting_position + ((3 + 4) * 4), flatten(t));
            index++;
        }
    });

    render();
}

//绘制图形

//绘制过程 必须经过 定点着色器（"vertex-shader"）和 片元着色器 （"fragment-shader"）
//定点着色器 把每一个顶点发送到GPU的光栅化模块中
//片元着色器 决定每一个决定的颜色

function render()
{
    gl.clear(gl.COLOR_BUFFER_BIT);                  //清理缓存

                                                    // 点 线 显示
    // gl.drawArrays(gl.POINTS, 0, points.length)   //点
    // gl.drawArrays(gl.LINES, 0, points.length)      //相邻2点连线
    // gl.drawArrays(gl.LINE_STRIP, 0, points.length)  // 第n点与n+1点连线
    // gl.drawArrays(gl.LINE_LOOP, 0, points.length)   //第n点与n+1点连线 最后n与1连线 闭合

                                                    // 多边形显示（三角形）
    // gl.drawArrays(gl.TRIANGLES, 0, points.length)   //相邻3点形成一个三角形
    // gl.drawArrays(gl.TRIANGLE_STRIP, 0, points.length)        //三角条带
    // gl.drawArrays(gl.TRIANGLE_FAN, 0, points.length)        //三角扇形

    gl.drawArrays(gl.POINTS, 0, index);

    window.requestAnimFrame(render);
}

function print_array(arr, level){
    var level = level || 1;
    var indent_str = ""
    for (var i = 1; i < level; i ++)
    {
		indent_str = indent_str + "&nbsp&nbsp&nbsp&nbsp"
    }
    
    print_text(indent_str + '{<br>');
	for(var key in arr){
		if(typeof(arr[key])=='array'||typeof(arr[key])=='object'){//递归调用  
			print_array(arr[key], level + 1);
		}else{
            print_text(indent_str + "&nbsp&nbsp&nbsp&nbsp" + key + ' = ' + arr[key] + '<br>');
		}
    }
    print_text(indent_str + '}<br>');
}

function print_text(text){
    document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + text;
}